package edu.washington.cs.sounddetector.server.c2dm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>
 * Handles saving of auth token for c2dm requests.
 * </p>
 * 
 * <p>
 * ClientAuthToken is threadsafe
 * </p>
 * 
 * @author the.dylan.price@gmail.com
 * 
 */
public class ClientAuthToken
{
    private static final Log log = LogFactory.getLog(C2DMessaging.class);

    private File authTokenFile;

    /**
     * Constructs a new ClientAuthToken.
     * 
     * @param authTokenFile
     *            the file where the auth token should be stored.
     */
    public ClientAuthToken(File authTokenFile)
    {
        this.authTokenFile = authTokenFile;
    }

    /**
     * @return the auth token currently set for this ClientAuthToken, or null if the auth token has
     *         never been set.
     */
    public synchronized String getAuthToken()
    {
        try
        {
            BufferedReader reader = new BufferedReader(new FileReader(authTokenFile));
            String authToken = reader.readLine();
            reader.close();
            return authToken;
        }
        catch (FileNotFoundException e)
        {
            log.error("FileNotFoundException", e);
            throw new RuntimeException(e);
        }
        catch (IOException e)
        {
            log.error("IOException", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Sets the auth token.
     * 
     * @param authToken
     *            the auth token to set.
     */
    public synchronized void setAuthToken(String authToken)
    {
        try
        {
            PrintWriter writer = new PrintWriter(new FileWriter(authTokenFile));
            writer.println(authToken);
            writer.flush();
            writer.close();
        }
        catch (FileNotFoundException e)
        {
            log.error("FileNotFoundException", e);
            throw new RuntimeException(e);
        }
        catch (IOException e)
        {
            log.error("IOException", e);
            throw new RuntimeException(e);
        }

    }
}
